import {useImmerState} from '../../hooks/useImmerState';
import {getCheckedList, setCheckInStatus} from '../../apis/checkin';
import useGlobal from '../../hooks/useGlobal';
import removeRepeat from '../../helpers/removeRepeat';


const useCheckInModel = (initialState = {
  allList: [],
  schoolList: [],
  typeList: [],
  unCheckedList: [],
  checkedList: [],
  rejectList: [],

}) => {
  const [state, setState] = useImmerState(initialState);
  const {state: globalState} = useGlobal();
  const getCardList = async () => {
    const res = await getCheckedList(globalState.login?.token);
    if (res.data.data.list?.length > 0) {
      setState(draft => {
        // 记录全部列表，用于导出数据
        draft.allList = res.data.data.list;
        draft.schoolList =
          removeRepeat(draft.allList.map(item => item.school_id));
        draft.typeList =
          removeRepeat(draft.allList.map(item => item.type));

        // 记录待审核列表
        draft.unCheckedList = res.data.data.list
          .filter(item => item.status === 2)
          .map((item, index) => ({...item, key: index}));

        // 记录已审核列表
        draft.checkedList = res.data.data.list
          .filter(item => item.status === 1)
          .map((item, index) => ({...item, key: index}));

        // 记录已驳回列表
        draft.rejectList = res.data.data.list
          .filter(item => item.status === 0)
          .map((item, index) => ({...item, key: index}));
      });
    }
  };

  const acceptCheckin = async (id, score) => {
    setCheckInStatus(
      globalState.login?.token,
      id,
      '1',
      score
    );
    getCardList();
  };

  const rejectCheckin = async (id) => {
    setCheckInStatus(
      globalState.login?.token,
      id,
      '0',
    );
    getCardList();
  };


  const effect = {
    getCardList,
    acceptCheckin,
    rejectCheckin
  };

  return {
    state,
    effect
  };
};

export default useCheckInModel;